/* ==================================================================   
 * Created [2009-4-27 下午11:32:55] by Jon.King 
 * ==================================================================  
 * TSS 
 * ================================================================== 
 * mailTo:jinpujun@hotmail.com
 * Copyright (c) Jon.King, 2009-2012 
 * ================================================================== 
*/

package com.jinhe.tss.core.cachepool.threadpool.arrayThreadPool;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

import com.jinhe.tss.core.cachepool.extend.assignment.IAssignment;


/**
 * <p> ArrayThreadPool.java </p>
 * 
 * 线程池（:池由一个数组简单实现）。</p><p>
 * 对池中的所有线程来说，它们都共享池的工作队列。</p><p>
 * 所以工作队列要求能实现同步，通过Collections.synchronizedList(new LinkedList())实现。</p><p>
 * 如果队列不为空的话，那么线程将反复的执行，来完成工作队列中的每个工作，直到工作队列为空。</p><p>
 * 
 * @author 金普俊 2007-1-9
 */

public class ArrayThreadPool {
    
    protected Logger log = Logger.getLogger(this.getClass());

    private final ThreadPoolWorker[] workers;
    private final List<IAssignment> workQueue;

    public ArrayThreadPool(int nThreads) {
        workQueue = Collections.synchronizedList(new LinkedList<IAssignment>());
        workers = new ThreadPoolWorker[nThreads];
        for (int i = 0; i < nThreads; i++) {
            workers[i] = new ThreadPoolWorker("Thread pool Worker " + i);
            workers[i].start();
        }
    }

    public void excute(IAssignment o) {
        log.debug("$$$ ArrayThreadPool.excute: " + o + "$$$");
        synchronized (workQueue) {
            workQueue.add(o);
            workQueue.notifyAll();  // workQueue在ThreadPoolWorker.run方法里wait()
        }
    }

    public class ThreadPoolWorker extends Thread {
        public ThreadPoolWorker(String name){
            super(name);
        }
        public void run() {
            IAssignment o;
            while (true) {
                synchronized (workQueue) {
                    while (workQueue.isEmpty()) {
                        try {
                            workQueue.wait();
                        } catch (InterruptedException ignored) {
                        }
                    }
                    o = (IAssignment) workQueue.remove(0); //将任务从队列中移除
                }
                // 执行任务队列中的任务，由ThreadPool中的一个Worker来执行
                try {
                    if (o != null) {
                        log.info("---" + this + ".run : " + o + "---");
                        o.excute();
                    }
                } catch (RuntimeException e) {
                } 
            }
        }

        public String toString(){
            return super.getName();
        }
    }
}
